import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter_ai/deepseek/x_chat_options.dart';
import 'package:flutter_ai/deepseek/x_message.dart';
import 'package:flutter_ai/deepseek/x_model.dart';
import 'package:flutter_ai/utils/https/x_https.dart';
import 'package:flutter_ai/utils/x_toast.dart';

///
/// deepseek 工具类
///
class XDeepSeek {
  final String apiKeys;

  XDeepSeek({
    required this.apiKeys,
  }) {
    // 设置请求头
    XHttps.getInstance().setHeaders({'Authorization': 'Bearer $apiKeys'});
  }

  ///
  /// 对话补全: https://api-docs.deepseek.com/api/create-chat-completion
  ///
  Future<XChatResponse?> createChatCompletion({
    required List<XMessage> messages,
    XChatModel model = XChatModel.chat,
    XChatOptions? options,
  }) async {
    if (apiKeys.trim().isEmpty) {
      XToast.showInfo('请填写 API KEYS');
      return null;
    }
    // 构建请求参数
    Map<String, dynamic> params = {
      'model': model.type,
      'messages': messages.map((e) => e.toMap()).toList(),
      ...options?.toMap() ?? {},
    };

    try {
      final res = await XHttps.getInstance().post('chat/completions', params: params);
      if (res.data != null) {
        return XChatResponse.fromJson(res.data);
      }
      return null;
    } on DioException catch (e) {
      final data = e.response?.data;
      if (data != null) {
        throw XException.fromBody(jsonEncode(data), e.response?.statusCode ?? -1);
      }
      throw XException.fromBody("{error: {message: Authentication Fails}}", -1);
    }
  }
}
